<template>
  <div class="loginBox">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="ruleForm"
      :style="{
        boxShadow: `var(${getCssVarName('lighter')})`,
      }"
      :size="formSize"
      status-icon
    >
      <el-form-item label="手机号" prop="phoneNumber">
        <el-input v-model="ruleForm.phoneNumber" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          登录
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { userLogin } from "@/api/user";
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
// 1.引入路由
import { useRouter } from "vue-router";

// 2. 获取路由实例（用于跳转）
const router = useRouter();

interface RuleForm {
  phoneNumber: string;
  password: string;
}

const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  phoneNumber: "",
  password: "",
});

const rules = reactive<FormRules<RuleForm>>({
  phoneNumber: [
    { required: true, message: "请输入用户手机号", trigger: "blur" },
    { min: 11, message: "长度必须是11位", trigger: "blur" },
    { max: 11, message: "长度必须是11位", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 18, message: "长度必须大于6位,小于18位", trigger: "blur" },
  ],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!" + ruleForm.phoneNumber + ":" + ruleForm.password);
      login();
    } else {
      console.log("error submit!", fields);
    }
  });
};

const login = async () => {
  const result = await userLogin(ruleForm);
  if (result.code === 200) {
    let token = result.data.token;
    let user = result.data.user;
    //将token存储到本地
    window.localStorage.setItem("token", token);
    window.localStorage.setItem("user", JSON.stringify(user));

    // 3.路由跳转到目标页面（如首页 /home）
    router.push({
      path: "/home",
    });
  } else {
    ElMessage.error("用户删除失败：" + (result.message || "未知错误"));
  }

  console.log(result);
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}));

// 添加背景阴影的
const getCssVarName = (type: string) => {
  return `--el-box-shadow${type ? "-" : ""}${type}`;
};
</script>

<style lang="scss" scoped>
.loginBox {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.ruleForm {
  width: 30%;
  padding: 50px 50px 20px 0px;
}
</style>
